package cn.wecloud.im.multiplayervideodemo

import android.app.*
import android.content.Context
import android.os.Bundle
import android.os.Process
import androidx.core.app.NotificationCompat
import cn.wecloud.im.WeCloud
import cn.wecloud.im.core.im.IMMessageManager
import cn.wecloud.im.multiplayervideodemo.act.MainActivity
import cn.wecloud.im.multiplayervideodemo.act.MeetAnswerActivity
import cn.wecloud.im.multiplayervideodemo.act.MultipleVideoActivity
import cn.wecloud.im.multiplayervideodemo.handler.MultiMeetMsgHandler
import cn.wecloud.im.multiplayervideodemo.utils.MyActivityLifeCycleCallbacks
import cn.wecloud.im.push.AndroidNotificationManager
import cn.wecloud.im.push.PushService
import com.facebook.stetho.Stetho
import com.facebook.stetho.common.LogRedirector
import java.util.*

class App : Application() {

    companion object {
        lateinit var instance: App


        //测试环境
        const val APP_KEY = "Sokb04m2MXqwATH3"
        const val APP_SECRET = "391413677bcf4105c87df6fbfa1310d1c8441c970ad2bcb0"
        const val MEDIA_SERVICE_URL = "wss://ws-meet-test.wecloud.cn"
        const val LIVE_URL = "http://121.37.22.224:8089"
        const val HTTP_URL = "https://imapitest.wecloud.cn/api/"
        const val WS_URL = "wss://imapitest.wecloud.cn/ws"
    }

    private val mActivitys = Stack<Activity>()

    override fun onCreate() {
        super.onCreate()

        val processName = getProcessName(this)
        //判断是当前APP进程
        if ("cn.wecloud.im.multiplayervideodemo" != processName) {
            //app其它资源的初始化
            return
        }
        instance = this
        //初始化SDK配置
        WeCloud.initialize(this, HTTP_URL, WS_URL)
        //注册多人会议事件处理
        IMMessageManager.registerMultiMeetMessageHandler(MultiMeetMsgHandler(this))

        //后台WS服务配置
        //设置自动唤醒
        PushService.setAutoWakeUp(true)
        //创建通知通道
        PushService.createNotificationChannel(
            this,
            "cn.wecloud.chatkitdemo",
            "后台运行",
            "消息渠道",
            NotificationManager.IMPORTANCE_HIGH,
            false,
            0,
            false,
            null
        )
        PushService.setDefaultChannelId(this, AndroidNotificationManager.DEFAULT_CHANNEL_ID)
        PushService.setForegroundMode(true, 123, createForegroundNotification())
        PushService.setDefaultPushCallback(this, MainActivity::class.java)
        PushService.setNotificationIcon(R.drawable.ic_launcher_foreground)

        Stetho.initializeWithDefaults(this)
        LogRedirector.setLogger(object : LogRedirector.Logger {
            override fun isLoggable(tag: String?, priority: Int) = false
            override fun log(priority: Int, tag: String?, message: String?) = Unit
        })
    }

    //获取进程名称
    private fun getProcessName(context: Context): String? {
        val am = context.getSystemService(ACTIVITY_SERVICE) as ActivityManager
        val runningApps = am.runningAppProcesses ?: return null
        for (proInfo in runningApps) {
            if (proInfo.pid == Process.myPid()) {
                if (proInfo.processName != null) {
                    return proInfo.processName
                }
            }
        }
        return null
    }

    private fun registerActivityLifeCallback() {
        registerActivityLifecycleCallbacks(object : MyActivityLifeCycleCallbacks() {
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
                mActivitys.add(activity)
            }

            override fun onActivityDestroyed(activity: Activity) {
                mActivitys.remove(activity)
            }

        })
    }

    private fun createForegroundNotification(): Notification {
        val builder =
            NotificationCompat.Builder(this, AndroidNotificationManager.DEFAULT_CHANNEL_ID)
                .setDefaults(NotificationCompat.FLAG_FOREGROUND_SERVICE)
                .setContentTitle("WeCloud Demo")
                .setContentText("后台连接已启用")
                .setPriority(NotificationCompat.PRIORITY_MIN)
                .setVibrate(longArrayOf(0))
                .setSound(null)
        return builder.setOngoing(true)
            .build()
    }

    fun isMultipleVideo(): Boolean {
        //在通话中或被邀请中
        val act = mActivitys.firstOrNull { it is MultipleVideoActivity || it is MeetAnswerActivity }
        return act != null
    }

    fun isMultiCall(): Boolean {
        val act = mActivitys.firstOrNull { it is MultipleVideoActivity } as? MultipleVideoActivity
        return act?.calling == true
    }

}